package br.com.millenium.domain.manager;

import java.math.BigInteger;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.persistence.Query;

import lumis.portal.PortalException;
import lumis.portal.UnexpectedException;
import lumis.portal.dao.jdbc.ITransactionJdbc;
import lumis.portal.manager.ManagerFactory;
import lumis.util.ITransaction;

public class EquipeManager implements IEquipeManager
{

	/*
	 * (non-Javadoc)
	 * @see br.com.millenium.domain.manager.IEquipeManager#isDuplicateEquipe(java.lang.String, java.lang.String, lumis.util.ITransaction)
	 */
	@Override
	public boolean isDuplicateEquipe(String equipeId, String equipeNome, ITransaction transaction) throws PortalException 
	{
		try
		{
			ITransactionJdbc daoTransactionJdbc = (ITransactionJdbc)transaction;
			Connection       connection         = daoTransactionJdbc.getConnection();
			
			PreparedStatement statement = connection.prepareStatement( "SELECT id FROM MM_Equipe WHERE nome = ? and id <> ?" );
			try
			{
				statement.setString(1, equipeNome);
				statement.setString(2, equipeId);
				
				ResultSet rs = statement.executeQuery();
				if( rs.next() )
					return true;
				else
					return false;
			}
			finally
			{
				statement.close();
			}
		}
		catch (Exception e)
		{
			throw new PortalException(e.getMessage());
		}
	}

	/*
	 * (non-Javadoc)
	 * @see br.com.millenium.domain.manager.IEquipeManager#isDeleteableEquipe(java.lang.String, lumis.util.ITransaction)
	 */
	public boolean isDeleteableEquipe(String equipeId, ITransaction transaction )	throws PortalException 
	{
		boolean returnValue = false;
		
		try 
		{
			String sql = "SELECT COUNT(id) AS total FROM MM_Definir_Equipe WHERE equipeId = ?";
			Query query = ManagerFactory.getEntityManager().createNativeQuery(sql);
			query.setParameter(1, equipeId);
			
			BigInteger result  = (BigInteger) query.getSingleResult();
			returnValue = (result.intValue() == 0);
		}
		catch (Exception e) 
		{
			throw new UnexpectedException(e);
		}
		
		return returnValue;
	}
}
